function hfile = prt_ConvertToVol(hfile, tr)
% PRT::ConvertToVol  - convert a ms-based PRT to volume-based
%
% FORMAT:       [prt] = prt.ConvertToVol(tr)
%
% Input fields:
%
%       tr          TR
%
% Output fields:
%
%       prt         altered protocol

% Version:  v0.7b
% Build:    7090213
% Date:     Sep-02 2007, 1:28 PM CEST
% Author:   Jochen Weber, Brain Innovation, B.V., Maastricht, NL
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 2 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'prt') || ...
   ~isa(tr, 'double') || ...
    numel(tr) ~= 1 || ...
    isinf(tr) || ...
    isnan(tr) || ...
    tr < 1 || ...
    tr ~= fix(tr)
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid call to %s.', ...
        mfilename ...
    );
end
bc = bvqxfile_getcont(hfile.L);

% return if not in volumes
if isempty(bc.ResolutionOfTime) || ...
    lower(bc.ResolutionOfTime(1)) ~= 'm'
    return;
end

% iterate over conditions
c = bc.Cond;
for cc = 1:numel(c)
    c(cc).OnOffsets = ...
        [round(c(cc).OnOffsets(:, 1) / tr) + 1, ...
         round(c(cc).OnOffsets(:, 2) / tr)];
    bv = find(c(cc).OnOffsets(:, 2) < c(cc).OnOffsets(:, 1));
    if ~isempty(bv)
        c(cc).OnOffsets(bv, 2) = c(cc).OnOffsets(bv, 1);
    end
end
bc.Cond = c;

% set to Volumes
bc.ResolutionOfTime = 'Volumes';
bvqxfile_setcont(hfile.L, bc);
